package com.ruc.deke.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.ruc.deke.model.DBRecord;
import com.ruc.deke.utils.DateKit;
import com.ruc.deke.utils.IpAddressUtil;
import com.ruc.deke.utils.ParseUtil;

@Controller
@RequestMapping(value = "/tracker")
public class TrackController {
	@Resource(name = "dataSource_rucdbcourse")
	private DataSource dataSource;

	@RequestMapping(value = "/moduleTrack")
	@ResponseBody
	public int moduleTrack(HttpServletRequest request, HttpSession session,
			@RequestParam(value = "moduleId") int moduleId,@RequestParam(value = "constmoduleId") int constmoduleId,
			@RequestParam(value = "actionId") int actionId) {
		String ip = IpAddressUtil.getIp(request);
		System.out.println(ip);
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println(moduleId);
		Statement statement = null;
		Connection connection = null;
		DBRecord record = new DBRecord();
		record.setField("MODULEID", String.valueOf(moduleId));
		record.setField("EXPID", "1");
		record.setField("TIME", new Date().toString());
		record.setField("USERID", String.valueOf(userId));
		record.setField("IP","in");
		
		DBRecord record1 = new DBRecord();
		record1.setField("MODULEID", String.valueOf(constmoduleId));
		record1.setField("EXPID", "1");
		record1.setField("TIME", new Date().toString());
		record1.setField("USERID", String.valueOf(userId));
		record1.setField("IP","out");
		try {
			String sql = ParseUtil.toInsertSQL("LOGS", record);
			String sql1 = ParseUtil.toInsertSQL("LOGS", record1);
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			statement.executeUpdate(sql);
			if(constmoduleId!=moduleId) {statement.executeUpdate(sql1);}
		} catch (SQLException e) {
			System.out.println("exception:" + e.getMessage());
		} catch (Exception e) {
			System.out.println("exception:" + e.getMessage());
		} finally {
			try {
				statement.close();
				connection.close();
			} catch (SQLException e) {
				System.out.println("exception:" + e.getMessage());
			}
		}
		return 0;
	}

	@RequestMapping(value = "/questionTrack")
	@ResponseBody
	public int questionTrack(HttpServletRequest request, HttpSession session,
			@RequestParam(value = "moduleId") int moduleId, @RequestParam(value = "questionId") String questionId,
			@RequestParam(value = "actionId") int actionId)
	{
		System.err.println("___________________________"+actionId);
		String ip = IpAddressUtil.getIp(request);
		System.out.println(ip);
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println(moduleId);
		Statement statement = null;
		Connection connection = null;
		DBRecord record = new DBRecord();
		record.setField("MODULEID", String.valueOf(moduleId));
		record.setField("EXPID", questionId);
		record.setField("TIME", new Date().toString());
		record.setField("USERID", String.valueOf(userId));
		record.setField("IP", String.valueOf(actionId));
		try
		{
			String sql = ParseUtil.toInsertSQL("LOGS", record);
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			statement.executeUpdate(sql);
		}
		catch (SQLException e)
		{
			System.out.println("exception:" + e.getMessage());
		}
		catch (Exception e)
		{
			System.out.println("exception:" + e.getMessage());
		}
		finally
		{
			try
			{
				statement.close();
				connection.close();
			}
			catch (SQLException e)
			{
				System.out.println("exception:" + e.getMessage());
			}
		}
		return 0;
	}

	/**
	 * 根据用户id和模块id得到每道题所用时间
	 * 
	 * @param moduleId
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/getTimeByModule")
	@ResponseBody
	public Object getTimeByModule(@RequestParam(value = "moduleId") String moduleId,
			@RequestParam(value = "userId") String userId) {
		System.out.println("hello");
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		ArrayList<DBRecord> records = new ArrayList<DBRecord>();
		try {
			String sql1 = "select count(*) as A from EXP_MODULE where MODULEID=" + moduleId;
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql1);
			records = ParseUtil.toDBRecord(resultSet);
			int num = records.get(0).getInt("A");//表中只有一个值
			System.out.println(num);
			long[] timeArr = new long[num];//用于记录时间
			String sql = "select * from logs where USERID=" + userId + " and MODULEID=" + moduleId +"ORDER BY TIME";
			resultSet = statement.executeQuery(sql);
			records = ParseUtil.toDBRecord(resultSet);
			statement.close();
			connection.close();
			//修改
			Long t1=(long) 0;//记录总停留时间
			Long t2=(long) 0;//暂存时间
			int t1flag=0;
			for (int i = 0; i < records.size() ; i++) {
				System.err.println(records.get(i).getString("MODULEID")+"###"+records.get(i).getString("EXPID")+"###"+records.get(i).getString("TIME")+"###"+records.get(i).getString("IP"));
				DBRecord dbRecord = records.get(i);
				int expid = dbRecord.getInt("EXPID");
				if(i<records.size()-1) {
				DBRecord dbRecord1 = records.get(i + 1);
				if (expid <= num) {
					if (expid != dbRecord1.getInt("EXPID")) {
						Long temp = DateKit.stringToDate(dbRecord1.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS").getTime()
							    	- DateKit.stringToDate(dbRecord.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS").getTime();
						if(temp<10000000)//限制因意外退出网页而造成的时间过大
							 timeArr[expid - 1] += temp / 1000;
					}
				}
				}
				if(dbRecord.getInt("EXPID")==1) {
					//System.err.println("#0.5"+dbRecord.getString("IP"));
					if(dbRecord.getString("IP").equals("in") && t1flag==0) {
						System.err.println("#1");
						t2=DateKit.stringToDate(dbRecord.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS").getTime();
						t1flag=1;
					}
					if(dbRecord.getString("IP").equals("out")) {
						System.err.println("#2");
						t1=DateKit.stringToDate(dbRecord.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS").getTime()-t2+t1;
						t1flag=0;
					}
				}
			}//for
			System.err.println(t1);
			if(t1>4000000)t1=(long) 0;
			timeArr[0] +=t1/1000;
			return timeArr;
		} catch (SQLException e) {
			System.out.println("exception:" + e.getMessage());
			return 0;
		}
	}

	/**
	 * 统计每个人在每个模块上所用的时间
	 * 
	 * @return
	 */
	@RequestMapping(value = "/timeAnalyse")
	@ResponseBody
	public Object timeAnalyse() {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		ArrayList<DBRecord> records = new ArrayList<DBRecord>();
		ArrayList<DBRecord> modules = new ArrayList<DBRecord>();
		Map<Integer, Map<Integer, Long>> timeMap = new HashMap<Integer, Map<Integer, Long>>();
		try {
			String sql1 = "select * from DB_COURSE_MODULE";
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql1);
			modules = ParseUtil.toDBRecord(resultSet);

			String sql = "select * from logs";
			resultSet = statement.executeQuery(sql);
			records = ParseUtil.toDBRecord(resultSet);
			statement.close();
			connection.close();
			for (int i = 0; i < records.size() - 1; i++) {
				DBRecord dbRecord = records.get(i);
				int userid = dbRecord.getInt("USERID");
				int moduleid = dbRecord.getInt("MODULEID");
				DBRecord dbRecord1 = records.get(i + 1);
				if (moduleid == dbRecord1.getInt("MODULEID")) {
					if (timeMap.get(userid) != null) {
						Map<Integer, Long> questionMap = timeMap.get(userid);
						if (questionMap.get(moduleid) != null) {
							Long temp = questionMap.get(moduleid)
									+ DateKit.stringToDate(dbRecord1.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS")
											.getTime()
									- DateKit.stringToDate(dbRecord.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS")
											.getTime();
							questionMap.put(moduleid, temp / 1000);
						} else {
							Long temp = DateKit.stringToDate(dbRecord1.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS")
									.getTime()
									- DateKit.stringToDate(dbRecord.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS")
											.getTime();
							questionMap.put(moduleid, temp / 1000);
						}
						timeMap.put(userid, questionMap);
					} else {
						Map<Integer, Long> questionMap = new TreeMap<Integer, Long>();
						Long temp = DateKit.stringToDate(dbRecord1.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS")
								.getTime()
								- DateKit.stringToDate(dbRecord.getString("TIME"), "yyyy-MM-dd HH:mm:ss.SSS").getTime();
						questionMap.put(moduleid, temp / 1000);
						timeMap.put(userid, questionMap);
					}
					System.out.println(dbRecord.getInt("MODULEID") + "----" + dbRecord.getInt("EXPID") + "-----"
							+ dbRecord.getInt("USERID") + "----" + dbRecord.getString("TIME"));
				}
			}

			return JSON.toJSON(timeMap);
		} catch (SQLException e) {
			System.out.println("exception:" + e.getMessage());
			return 0;
		}
	}
}
